<template>
<view class="product-details-box h100 bg-white text-black" :class="ifShowProductModal ? 'ovh' : ''">
<!-- <scroll-view scroll-y class="product-details-box" @scroll="onScroll"> -->
  <!-- 商品图片和信息 -->
  <view class="product-summary">
    <view class="product-image-swiper">
      <swiper class="screen-swiper round-dot" :indicator-dots="true" :circular="true" :autoplay="true">
        <swiper-item v-for="(imgsrc,index) in productImageList" :key="index">
          <image :src="BASE_URL + imgsrc" mode="aspectFill"></image>
        </swiper-item>
      </swiper>
    </view>
    <view class="product-info padding bg-white">
      <view class="title">
        <view class="label text-lg">
          <!-- <view class="cu-tag line-red radius margin-right text-lg">全新</view> -->
          {{productInfo.title}}
        </view>
      </view>
      <view class="subtitle text-sm text-gray margin-tb-sm">
        官方售价: <text class="margin-lr-xs">{{productInfo.price}}元</text>
        <!-- 到期买断价: {{productInfo.buyoutprice}}元 -->
      </view>
      <view class="desc flex justify-between align-end">
        <view class="price text-price main-color text-xxl">{{productInfo.avg_price}}/{{RETUNIT_LIST[productInfo.rentunit]}}</view>
        <view class="remark text-gray text-df">{{productInfo.isnodeposit ? '可免' : productInfo.nodeposit }}押金&nbsp;&nbsp;|&nbsp;&nbsp;{{productInfo.rentday}}{{RETUNIT_LIST[productInfo.rentunit]}}起租</view>
      </view>
    </view>
  </view>
  <!-- 当前选中的套餐和配送方式 -->
  <view class="product-selected margin-top-sm">
    <view class="cu-list menu">
      <view class="cu-item arrow" @tap="showModal">
        <view class="content">
          <text class="">套餐</text>
        </view>
        <view class="action">
          <text class="text-gray">{{productAttrSelectedLabel}}</text>
        </view>
      </view>
      <!-- <view class="cu-item arrow">
        <view class="content">
          <text class="">配送方式</text>
        </view>
        <view class="action">
          <text class="text-gray">顺丰/韵达/申通、运费到付</text>
        </view>
      </view> -->
    </view>
  </view>
  <!-- 租赁周期/商品简介 -->
  <view class="product-details-info bg-white margin-top-sm">
    <scroll-view scroll-x class="bg-white nav margin-bottom-sm border-bottom">
      <view class="text-center">
        <view class="cu-item margin-lr-xl" :class="index == curNavIndex ? 'text-orange cur' : '' " v-for="(item,index) in navList" :key="index" @tap="navSelect" :data-value="item.value">
          {{item.label}}
        </view>
      </view>
    </scroll-view>
    <view class="product-details-info-content flex justify-center" v-if="ifShowProductDetailInfo" style="webkit-overflow-scrolling: touch;overflow-y: scroll;">
      <image :src="productInfo.content" mode="widthFix" @load="onLoadProductDetailInfoImg"></image>
      <!-- <lazy-img :src="productInfo.content" mode="widthFix"></lazy-img> -->
    </view>
    <dm-rentStatement v-if="!ifShowProductDetailInfo"></dm-rentStatement>
  </view>

  <!-- 操作按钮 -->
  <view class="product-actions">
    <button class="cu-btn comment" @tap="gotoCustomerService">
      <text class="cuIcon-comment"></text>
    </button>
    <button class="cu-btn order text-white" @tap="onOrder">
      <text class="cuIcon-lightfill margin-right-sm"></text>
      <text class="text-xxl">立即租</text>
    </button>
  </view>

  <!-- 下单模态框 -->
  <view id="product-modal" class="cu-modal bottom-modal" :class="ifShowProductModal ? 'show' : ''">
    <view class="cu-dialog bg-white padding-tb">
      <view class="header flex justify-start padding-lr text-black">
        <view class="product-img bg-gray">
          <lazy-img v-if="productInfo.image_logo" :src="`${BASE_URL}${productInfo.image_logo}`" mode="widthFix"></lazy-img>
        </view>
        <view class="info text-sm margin-left-sm">
          <view class="product-price main-color text-price text-xxl">
            <template v-if="ifRented">{{productInfo.avg_price}}/{{RETUNIT_LIST[productInfo.rentunit]}}</template>
            <template v-if="!ifRented">{{productInfo.price * amount}}</template>
          </view>
          <view class="margin-top-xs">库存{{productInfo.stock}}件</view>
          <view class="margin-top-xs">{{productAttrSelectedLabel}}</view>
        </view>
        <view class="close">
          <text class="cuIcon-close" @tap="closeModal"></text>
        </view>
      </view>

      <view class="product-modal-content padding-lr text-black">
        <dm-radio v-for="(attrItem, index) in productAttr" :target="attrItem" :key="index" :label="attrItem.attr_name" :options="attrItem.attr_options" :selected="attrItem.selected" @onSelect="onSelectedProductAttr"></dm-radio>
        <dm-radio label="租期" :options="[rentLabel]" :selected="0" :disabled="!ifRented"></dm-radio>

        <!-- <form>
          <view class="cu-form-group dm-bar">
            <view class="text-sm">自定义租期</view>
          </view>
          <view class="cu-form-group">
            <view class="title">起租时间</view>
            <picker mode="date" :value="startDate" start="2015-09-01" end="2020-09-01" @change="startDateChange">
              <view class="picker">
                {{startDate}}
              </view>
            </picker>
          </view>
          <view class="cu-form-group border-bottom">
            <view class="title">结束时间</view>
            <picker mode="date" :value="endDate" start="2015-09-01" end="2020-09-01" @change="endDateChange">
              <view class="picker">
                {{endDate}}
              </view>
            </picker>
          </view>
        </form> -->

        <view class="amount flex justify-between margin-tb">
          <view class="title" v-if="ifRented">租赁数量</view>
          <view class="title" v-if="!ifRented">购买数量</view>
          <uni-number-box class="dm-numbox" :min="1" :max="productInfo.stock" :value="amount" @change="amountChange" :disabled="ifRented"></uni-number-box>
        </view>

        <view class="instalment-box">
          <dm-radio label="分期" :options="instalmentOptions" :selected="instalment" @onSelect="onInstalmentChange"></dm-radio>

          <view class="cu-list menu" v-if="ifRented">
            <view class="cu-item border-bottom" @tap="toggleInstalmentList">
              <view class="content">
                <text class="text-sm">每期还款</text>
              </view>
              <view class="action">
                <text class="text-black text-sm" :class="ifShowInstalment ? 'cuIcon-unfold' : 'cuIcon-fold'"></text>
              </view>
            </view>
          </view>

          <view class="instalment-details" v-if="ifShowInstalment">
            <view class="instalment-item flex justify-between margin-top-xs text-xs text-orange" v-for="(item, index) in instalmentPlan" :key="index">
              <text>第{{item.stages}}期</text>
              <text>-</text>
              <text>-</text>
              <text class="text-price">{{item.price}}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="actions padding-lr padding-top margin-top flex flex-direction">
        <view class="agreement flex align-center">
          <checkbox class='orange' :class="ifAgree ? 'checked' : ''" :checked="ifAgree" value="A" style="transform:scale(0.5)" @tap="agreementChange"></checkbox>
          <!-- <view class="text-xs">点击勾选代表您已同意<text class="text-orange" @tap="previewProtocol(1)">《租赁服务协议》</text>和<text class="text-orange">《个人征信授权书》</text>和<text class="text-orange">《委托担保申请》</text></view> -->
          <view class="text-xs">点击勾选代表您已同意<text class="text-orange" @tap="previewProtocol(1)">《租赁服务协议》</text></view>
        </view>

        <button type="" class="cu-btn dm-btn round bg-orange margin-tb-sm text-lg" @tap="onCreateOrder" :disabled="!ifOkToOrder">确认</button>
      </view>

    </view>
  </view>

<!-- </scroll-view> -->
</view>
</template>

<script>
import dmRadio from '@/components/dm-radio/dm-radio'
import dmRentStatement from '@/components/dm-rentStatement/dm-rentStatement'
import uniNumberBox from "@/components/uni-number-box/uni-number-box.vue"
import { mapState, mapGetters } from 'vuex'

export default {
  name: 'product-details', // 商品详情
  components: {
    dmRadio,
    uniNumberBox,
    dmRentStatement
  },
  data () {
    return {
      curId: 0,
      productDetails: {},
      ifShowProductModal: false,
      curNavIndex: 0,
      scrollLeft: 0,
      navList: [
        {
          value: 0,
          label: '商品简介'
        },
        {
          value: 1,
          label: '租赁周期'
        }
      ],
      /** 购买数量 */
      amount: 1,
      /** 产品所选的分期(0: 分期, 1: 买断) */
      instalment: 0,
      ifShowInstalment: false,
      startDate: '2020-02-13',
      endDate: '2020-02-13',
      ifAgree: false,
      myWebView: null
    }
  },
  computed: {
    ...mapState([
      'BASE_URL',
      'RETUNIT_LIST',
      'PRODUCT_TYPE_LIST'
    ]),
    ...mapGetters([
      'hasLogin'
    ]),
    /** 产品信息 */
    productInfo() {
      let target = this.productDetails.info || {}
      this.$store.commit('SET_PRODUCT_INFO', target)
      return target
    },
    /** 订单分期选项 */
    instalmentOptions() {
      let target = []
      if (this.productInfo.count) {
        target = this.productInfo.count.split('*')
        target.pop() // 删除最后一个'买断'选项
      }
      return target
    },
    /** 产品分期计划 */
    instalmentPlan() {
      let target = this.productDetails.plan || {}
      return target
    },
    /** 是否租赁 */
    ifRented() {
      // 这个判断基于返回数据只有2个选项(3期*买断)
      return this.instalment == 0
    },
    rentLabel() {
      return this.productInfo.rentday + this.RETUNIT_LIST[this.productInfo.rentunit]
    },
    /** 产品属性(型号, 颜色, 容量等) */
    productAttr() {
      let target = this.productDetails.attr || []
      if (target.length) {
        target.map(item => {
          item.attr_options = item.attr_value.split('*')
          item.selected = 0
        })
      }
      return target
    },
    productImageList() {
      let target = []
      if (this.productInfo.images) {
        target = this.productInfo.images.split(',')
      }
      return target
    },
    orderParams() {
      let target = {
        goods_id: this.curId,
        number: this.amount,
        isfullone: this.instalment,
        specs_value: []
      }
      let specsArr = []
      if (this.productAttr.length) {
        this.productAttr.forEach(item => {
          specsArr.push({
            attr_name: item.attr_name,
            attr_value: item.attr_options[item.selected]
          })
        })
      }
      // 后台接口需要, 把产品属性参数转为字符串
      target.specs_value = JSON.stringify(specsArr)
      
      if (this.ifRented) { // 租赁订单
        target.rentday = this.productInfo.rentday
        target.rentunit = this.productInfo.rentunit
        target.stagesnumber = this.productInfo.rent_cont
      }
      return target
    },
    /** 产品属性选中的显示文本 */
    productAttrSelectedLabel() {
      let target = '已选:'
      if (this.productAttr.length) {
        this.productAttr.forEach(item => {
          if (item.selected >= 0) {
            target += `${item.attr_options[item.selected]} `
          }
        })
      }
      if (this.ifRented) {
        target += this.rentLabel + ' '
      }
      target += this.instalmentOptions[this.instalment]
      console.log('属性', target)
      return target
    },
    ifShowProductDetailInfo() {
      return this.curNavIndex == 0
    },
    ifOkToOrder() {
      let flag = true
      this.productAttr.forEach(item => {
        if (item.selected === -1) { // 判断是否有未选择的属性
          flag = false
          return flag
        }
      })
      return this.ifAgree && flag
    }
  },
  watch: {
    curId() {
      this.getProductDetail()
    },
    ifRented(newValue) {
      if (newValue) {
        this.amount = 1
      }
    }
  },
  onLoad() {
    console.log('onLoad, id:', this.$Route.query.id)
    this.curId = this.$Route.query.id
  },
  methods: {
    onScroll(event) {
      // console.log('onScroll', event)
    },
    /** 获取产品详情 */
    getProductDetail() {
      const params = {
        id: this.curId
      }
      return new Promise(resolve => {
        this.$api.getProductDetail(params).then(res => {
          console.log('获取产品详情', res)
          if (!res) return
          this.productDetails = res.data
        })
      })
    },
    /** 选择产品属性 */
    onSelectedProductAttr() {
    },
    onOrder() {
      console.log('点击立即租')
      this.showModal()
    },
    navSelect(e) {
      this.curNavIndex = e.currentTarget.dataset.value
      this.scrollLeft = (e.currentTarget.dataset.value - 1) * 60
    },
    gotoCustomerService() {
      this.$Router.push({ name: 'customer-service' })
    },
    onCreateOrder() {
      if (this.hasLogin) { // 判断是否有登录
        this.$store.commit('SET_ORDER_PARAMS', this.orderParams)
        this.$Router.push({ name: 'order-create' })
      } else {
        this.gotoEntrance()
      }
    },
    async previewProtocol(type) {
      const url = await this.getProtocolUrl(type)
      if (!url) return
      // #ifdef APP-PLUS
      uni.downloadFile({
        url,
        success: res => {
          const filePath = res.tempFilePath
          uni.openDocument({
            filePath: filePath,
            success: res => {
              console.log('打开文档成功')
              // this.$showSuccessToast('打开文档成功')
            }
          })
        }
      })
      // #endif

      // this.$Router.push({
      //   name: 'webView',
      //   params: {
      //     mode: 'protocol',
      //     type,
      //     url
      //   }
      // })
    },
    getProtocolUrl(type) {
      return new Promise(resolve => {
        const params = {
          product_id: this.curId,
          type
        }
        this.$api.previewProtocol(params).then(res => {
          console.log('协议', res)
          if (!res) return
          const url = res.data && res.data.url
          resolve(url)
        })
      })
    },
    onLoadProductDetailInfoImg() {
      console.log('!!---图片简介加载--!!')
    },
    amountChange(number) {
      this.amount = number
    },
    onInstalmentChange(index) {
      console.log('onInstalmentChange', index, typeof index)
      this.instalment = index
    },
    gotoEntrance() {
      this.$Router.push({
        name: 'entrance',
        animation:{
          animationType:'slide-in-bottom',
          animationDuration: 300
        }
      })
    },
    startDateChange(e) {
      this.startDate = e.detail.value
    },
    endDateChange(e) {
      this.endDate = e.detail.value
    },
    /** 切换显示分期详情 */
    toggleInstalmentList() {
      this.ifShowInstalment = !this.ifShowInstalment
    },
    agreementChange() {
      this.ifAgree = !this.ifAgree
    },
    showModal() {
      this.ifShowProductModal = true
    },
    closeModal() {
      this.ifShowProductModal = false
    }
  }
}
</script>

<style lang="less">
.product-details-box {
  position: relative;
}
/** 商品详情 Start */
.product-image-swiper {
  width: 100%;
  height: 750rpx;

  .screen-swiper {
    height: 750rpx;
  }
}

.product-details-info {
  padding-bottom: 100rpx;
  &-content {
    // height: 100vh;
    .content-iframe {
      width: 100%;
      height: 100%;
    }
  }

  .nav .cu-item {
    margin-left: 60rpx;
    margin-right: 60rpx;
  }
}


.product-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;

  .comment {
    width: 30%;
    height: 100rpx;
    font-size: 30px;
    color: #ffc27e;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }

  .order {
    width: 70%;
    height: 100rpx;
    font-size: 28px;
    background: #ffc27e;
    color: #fff;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
}
/** 商品详情 End */

/** 立即租 Start */
#product-modal {
  text-align: left;

  &.cu-modal {
    z-index: 800;
  }

  .cu-form-group {
    padding: 0;
    .title {
      font-size: 14px;
    }
  }

  .cu-list.menu>.cu-item {
    padding: 0;
  }

  .cu-dialog {
    border-top-left-radius: 36rpx;
    border-top-right-radius: 36rpx
  }

  .header {
    position: relative;
    height: 180rpx;
    border-bottom: 2rpx solid #eee;

    .product-img {
      width: 160rpx;
      height: 160rpx;
    }

    .close {
      position: absolute;
      right: 30rpx;
      top: 0;
    }
  }

  .product-modal-content {
    min-height: 450rpx;
    max-height: 50vh;
    overflow-y: scroll;
  }

  .dm-bar {
    min-height: 60rpx;
    padding: 0;
  }

  .actions {
    width: 100%;
    height: 220rpx;
  }

  .product-price {
    height: 60rpx;
  }
}
/** 立即租 End */
</style>
